<?php
namespace app\admin\controller;
use think\Db;
use clt\Tree;
use think\Request;
use think\Controller;
class Course extends Common
{
    public function _initialize(){
        parent::_initialize();
    }
    //列表页
    public function index(){
        if(request()->isPost()) {
            $key = input('post.key');
            $this->assign('testkey', $key);
            $page =input('page')?input('page'):1;
            $pageSize =input('limit')?input('limit'):config('pageSize');
            $list = Db::name('course')
                ->where('course_name', 'like', "%" . $key . "%")
                ->order('sort DESC')
                ->paginate(array('list_rows'=>$pageSize,'page'=>$page))
                ->toArray();
            foreach ($list['data'] as $k=>$v){
                $list['data'][$k]['addtime'] = date('Y-m-d H:s',$v['addtime']);
            }
            return $result = ['code'=>0,'msg'=>'获取成功!','data'=>$list['data'],'count'=>$list['total'],'rel'=>1];
        }
        return $this->fetch();
    }

    //获取发布栏目
    public function getCat(){
        if(request()->isAjax()){
            $key = input('post.key');
            $this->assign('testkey', $key);
            $catlsit = db('category')
                ->where('name', 'like', "%" . $key . "%")
                ->field('cate_id,name,parent_id')
                ->select();
            $tree = new Tree ($catlsit);
            //p($catlsit);
            $categorys = $tree->recursion(0);
            $nbsp="&nbsp;&nbsp;&nbsp;&nbsp;";
            $str = "";
            foreach($categorys as $k=>$v){
                $str.="<h3><a href='javascript:;' data-id='{$v['cate_id']}' data-name='{$v['name']}'>{$v['name']}</a></h3>";
                if(is_array($v['son'])){
                    $str.="<p>";
                    foreach($v['son'] as $k1=>$v1){
                        $str.="&nbsp;&nbsp;&nbsp;├─&nbsp; <a href='javascript:;' data-id='{$v1['cate_id']}' data-name='{$v1['name']}'>{$v1['name']}</a>{$nbsp}";
                        if(is_array($v1['son'])){
                            $str.="<p>";
                            foreach($v1['son'] as $k2=>$v2){
                                $str.="<a href='javascript:;' data-id='{$v2['cate_id']}' data-name='{$v2['name']}'>&nbsp;&nbsp;&nbsp;├─&nbsp;├─&nbsp; {$v2['name']}{$nbsp}</a>";
                            }
                            $str.="</p>";
                        }
                    }
                    $str.="</p>";
                }
            }
            //$this->assign('actList',$str);
            echo $str;
        }else{
            $catlsit = db('category')
                ->field('cate_id,name,parent_id')
                ->select();
            $tree = new Tree ($catlsit);
            $categorys = $tree->recursion(0);
            $nbsp="&nbsp;&nbsp;&nbsp;&nbsp;";
            $str = "";
            foreach($categorys as $k=>$v){
                $str.="<h3><a href='javascript:;' data-id='{$v['cate_id']}' data-name='{$v['name']}'>{$v['name']}</a></h3>";
                if(is_array($v['son'])){
                    $str.="<p>";
                    foreach($v['son'] as $k1=>$v1){
                        $str.="&nbsp;&nbsp;&nbsp;├─&nbsp; <a href='javascript:;' data-id='{$v1['cate_id']}' data-name='{$v1['name']}'>{$v1['name']}</a>{$nbsp}";
                        if(is_array($v1['son'])){
                            $str.="<p>";
                            foreach($v1['son'] as $k2=>$v2){
                                $str.="<a href='javascript:;' data-id='{$v2['cate_id']}' data-name='{$v2['name']}'>&nbsp;&nbsp;&nbsp;├─&nbsp;├─&nbsp; {$v2['name']}{$nbsp}</a>";
                            }
                            $str.="</p>";
                        }
                    }
                    $str.="</p>";
                }
            }
            $this->assign('actList',$str);
            return $this->fetch();
        }
    }

    //设置课程发布时间
    public function setTime(){
        $timeDate = input('timeDate');
        $year = date('Y'); //获取当前年
        $onMonth = date('m'); //获取当前月
        $onMonth = floor($onMonth-1);
        $onDay = date('d'); //获取当前月
        $onDay = floor($onDay-1);
        //p($onMonth);
        //定义一个24小时数组
        $hour = array(
            '00:00','00:30','01:00','01:30','02:00','02:30','03:00',
            '03:30','04:00','04:30','05:00','05:30','06:00','06:30',
            '07:00','07:30','08:00','08:30','09:00','09:30','10:00',
            '10:30','11:00','11:30','12:00','12:30','13:00','13:30',
            '14:00','14:30','15:00','15:30','16:00','16:30','17:00',
            '17:30','18:00','18:30','19:00','19:30','20:00','20:30',
            '21:00','21:30','22:00','22:30','23:00','23:30'
            );

        for($i=1;$i<=12;$i++){
            $days = cal_days_in_month(CAL_GREGORIAN, $i, $year);
            for($j=1; $j<=$days; $j++){
                $arrDay[$i-1][] = $j.'号';
            }
        }

        $month = array(
            'month'=>array('1月份','2月份','3月份','4月份','5月份','6月份','7月份','8月份','9月份','10月份','11月份','12月份'),
            'month_day'=>$arrDay
        );

        $this->assign('timeDate',$timeDate);    //父级页面的表单日期数组
        $this->assign('year',$year);     //年份
        $this->assign('onDay',$onDay);     //当月天
        $this->assign('onMonth',$onMonth); //当月
        $this->assign('month',$month);
        return $this->fetch();
    }

    //获取月份天数
    public function getDay(){
        $month = input('month');

        $year = date('Y');
        $days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
        $str = '';
        for($i=1;$i<=$days;$i++){
            $str.= " <span class=\"box\"><input type=\"checkbox\" name=\"mark[{$i}]\" lay-skin=\"primary\" title=\"{$i}号\" ></span>";
        }

        $data = array(
           'code'=>200,
            'str'=> $str
        );
        return json($data);
    }

    //数据添加
    public function add(){
        if(request()->isPost()) {
            //构建数组
            $data = input('post.');
            $data['addtime'] = time();    //添加时间
            $data['status'] = 0;           //状态,默认待审核
            $data['agency_id'] = session('agency_id');  //机构ID
            $data['addtime'] = time();     //添加时间
            $data['course_sn'] = 'kc_'.date('YmdHis',time()).rand_string('3',1);     //课程编号



            //通过提交过的栏目ID,获取其家族路径
            $parent_id_path = db('category')->where('cate_id',$data['cat_id'])->value('parent_id_path');
            $path_arr = explode(',',$parent_id_path);

            if(is_array($path_arr)){
                if($path_arr[1] > 0 ){
                    $data['cat_id1'] = $path_arr[1];   //一级类别id
                }

                if($path_arr[2] > 0 ){
                    $data['cat_id2'] = $path_arr[2];   //二级类别id
                }

                if($path_arr[3] > 0 ){
                    $data['cat_id3'] = $path_arr[3];    //三级类别id
                }
            }
            $row =  db('course')->insert($data);     //添加数据
            $in_id = db('course')->getLastInsID();   //获取插入的ID
            //课程内容插入成功,将关联的开课时间也插入到数据库中
            if($row){
                //处理要插入关联表的数据
                if(is_array($data['data'])){
                    foreach($data['data'] as $k=> $v){
                        $tmap[$k]['course_id'] = $in_id;
                        $tmap[$k]['course_time'] = $v;
                    }

                    foreach($data['number_s'] as $k=> $v){
                        $tmap[$k]['limit_num'] = $v;
                    }

                    //循环插入时间表
                    foreach($tmap as $k=> $v){
                        db('course_time')->insert($v);
                    }
                }
            }

            $result['code'] = 1;
            $result['msg'] = '课程添加成功,等待后台审核';
            $result['url'] = url('index');
            return $result;
        }else{


            //$this->assign('adtypeList',json_encode($adtypeList,true));

            $this->assign('title','课程添加成功!');
            $this->assign('info','null');
            return $this->fetch('form');
        }
    }

    //数据修改
    public function edit(){
        if(request()->isPost()) {
            $data = input('post.');
            //通过提交过的栏目ID,获取其家族路径
            $parent_id_path = db('category')->where('cate_id',$data['cat_id'])->value('parent_id_path');
            $path_arr = explode(',',$parent_id_path);

            if(is_array($path_arr)) {
                if ($path_arr[1] > 0) {
                    $data['cat_id1'] = $path_arr[1];   //一级类别id
                }

                if ($path_arr[2] > 0) {
                    $data['cat_id2'] = $path_arr[2];   //二级类别id
                }

                if ($path_arr[3] > 0) {
                    $data['cat_id3'] = $path_arr[3];    //三级类别id
                }
            }
            $row = db('course')->update($data);
            //课程内修改成功,通过course_id 删除关联时间表里面的所有关联数据,再重新插入新数据
            if($row){
                //先删除之前的关联数据
                db('course_time')->where('course_id',$data['course_id'])->delete();

                //处理要插入关联表的数据
                if(is_array($data['data'])) {
                    foreach ($data['data'] as $k => $v) {
                        $tmap[$k]['course_id'] = $data['course_id'];
                        $tmap[$k]['course_time'] = $v;
                    }

                    foreach ($data['number_s'] as $k => $v) {
                        $tmap[$k]['limit_num'] = $v;
                    }

                    //循环插入时间表
                    foreach ($tmap as $k => $v) {
                        db('course_time')->insert($v);
                    }
                }
            }


            $result['code'] = 1;
            $result['msg'] = '课程修改成功!';
            $result['url'] = url('index');
            return $result;
        }else{

            $course_id=input('course_id');

            //1.查询课程信息
            $adInfo=db('course')->where(array('course_id'=>$course_id))->find();

            //2.查询关联的栏目名称
            if($adInfo['cat_id3'] > 0){
                $catInfo = db('category')->field('cate_id,name')->where('cate_id',$adInfo['cat_id3'])->find();
            }else if($adInfo['cat_id2'] > 0){
                $catInfo = db('category')->field('cate_id,name')->where('cate_id',$adInfo['cat_id2'])->find();
            }else if($adInfo['cat_id1'] > 0){
                $catInfo = db('category')->field('cate_id,name')->where('cate_id',$adInfo['cat_id1'])->find();
            }

            //3.查询关联的课程时间信息
            if($adInfo['course_id'] >  0){
                $tileList = db('course_time')
                    ->whereTime('course_time', '>=', date('Y-m-d'))
                    ->where('course_id',$adInfo['course_id'])
                    ->select();
            }

            //处理一下时间格式
            foreach($tileList as $k => $v){
                $tileList[$k]['course_time'] = date('Y-m-d', strtotime($v['course_time']));
            }

            $this->assign('info',json_encode($adInfo,true));
            $this->assign('catInfo',$catInfo);
            $this->assign('tileList',$tileList);
            $this->assign('title',lang('edit').'课程');
            $this->assign('course_id',$course_id);
            $this->assign('edit','edit');  //传一个修改参数过去
            return $this->fetch('form');
        }
    }

    //修改状态
    public function editState(){
        $id=input('post.id');
        $open=db('course')->where(array('course_id'=>$id))->value('open');//判断当前状态情况
        if($open==1){
            $data['open'] = 0;
            db('course')->where(array('course_id'=>$id))->setField($data);
            $data['status'] = 1;
        }else{
            $data['open'] = 1;
            db('course')->where(array('course_id'=>$id))->setField($data);
            $data['status'] = 1;
        }
        return $data;
    }

    //修改排序
    public function adOrder(){
        $course=db('course');
        $data = input('post.');
        if($course->update($data)!==false){
            return $result = ['msg' => '操作成功！','url'=>url('index'), 'code' =>1];
        }else{
            return $result = ['code'=>0,'msg'=>'操作失败！'];
        }
    }

    public function del(){
        db('course')->where(array('course_id'=>input('course_id')))->delete();
        return ['code'=>1,'msg'=>'删除成功！'];
    }

    public function delall(){
        $map['course_id'] =array('in',input('param.ids/a'));
        db('course')->where($map)->delete();
        $result['msg'] = '删除成功！';
        $result['code'] = 1;
        $result['url'] = url('index');
        return $result;
    }

    //修改栏目状态
    public function editStatus(){
        $data =  input('post.');
        //p($data);
        if($data['status'] == 'false'){
            $map['status'] = 2;
            $row = db('course')->where('course_id',$data['course_id'])->update($map);
            if($row > 0 ){
                $data  = array(
                    'code' => 1,
                    'msg'  =>  '已取消审核',
                    'url'  => url('index'),
                );
                return $data;
            }
        }else{
            $map['status'] = 1;
            $row = db('course')->where('course_id',$data['course_id'])->update($map);
            if($row > 0 ){
                $data  = array(
                    'code' => 1,
                    'msg'  =>  '审核通过',
                    'url'  => url('index'),
                );
                return $data;
            }
        }

        $data  = array(
            'code' => 0,
            'msg'  =>  '操作失败',
            'url'  => url('index'),
        );
        return $data;

    }
}